package com.lollipop.common.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lollipop.common.persistence.BaseModel;
import com.lollipop.common.persistence.CrudDao;
import com.lollipop.common.utils.Identities;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Transactional(readOnly = true)
public abstract class CrudServiceImpl<D extends CrudDao<T>, T extends BaseModel<T>> implements CrudService<T> {

    @Autowired
    protected D dao;


    @Override
    public T get(String id) {
        return dao.get(id);
    }

    /**
     * 查询列表数据
     *
     * @param entity
     * @return
     */
    public List<T> findList(T entity) {
        return dao.findList(entity);
    }


    public PageInfo<T> findPager(int pageNo, int pageSize, T args) {
        PageHelper.startPage(pageNo, pageSize);
        return new PageInfo<T>(dao.findList(args));
    }


    /**
     * 保存数据（插入或更新）
     *
     * @param entity
     */
    @Transactional(readOnly = false)
    public void saveOrUpdate(T entity) {
        if (entity.isNew()) {
            entity.setId(Identities.uuid2());
            dao.insert(entity);
        } else {
            dao.update(entity);
        }
    }

    /**
     * 删除数据
     *
     * @param entity
     */
    @Transactional(readOnly = false)
    public void delete(T entity) {
        dao.delete(entity);
    }

    @Override
    public void init() {
        //初始化执行方法
        log.debug(">>>>初始化执行.");
    }
}
